import loadding from "@/utils/common.js"
import {BASE_PATH} from "@/utils/config.js"
import {getStorage} from '@/utils/common.js'

let host = ""

host = BASE_PATH

const timeout = 90000;


function objectToQueryString(obj) {

	return Object.keys(obj).map(function(key) {

		return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(obj[key]));

	}).join('&');

}

function _request(options) {

	let requestConf = {
		method: options.method ? options.method : 'POST',
		url: host + options.url,
		timeout: timeout,
		success(ret) {
			if (!options.closeLoading) {
				loadding.hide();
			}
			// if(ret.data.msg.indexOf('非法访问')>-1 || ret.data.msg.indexOf('token解析失败')>-1){
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '您还未登录，请使用当前微信登录！',
			// 		showCancel: false,
			// 		success: async (res)=> {
			// 			uni.reLaunch({
			// 				url:'/pages/login/login'
			// 			})
			// 		}
			// 	})
			// }else {
			// 	options.success(ret.data);
			// }
			if (ret.data.code==200) {
				options.success(ret.data);
			}else {
				options.fail && options.fail(ret.data);
			}
		},
		fail(err) {
			if (!options.closeLoading) {
				loadding.hide();
			}
			//console.log(err);
			options.fail && options.fail(err);
		},
		complete() {
			
		}
	}


	if (!options.data) {
		options.data = {};
	}

	if (options.params) {
		requestConf['url'] += '?' + objectToQueryString(options.params);
	}

	requestConf['data'] = options.data

	if (!options.type) {
		options.type = 'json';
	}
	if (options.type == 'json') {
		requestConf['dataType'] = 'json';
	}

	// header 头配置
	requestConf['header'] = {
		'Content-Type': options.type != 'json' ? 'application/x-www-form-urlencoded' : 'application/json',
	}
	const userInfo = JSON.parse(getStorage('userInfo') || '{}') 
	if (userInfo && userInfo.token) {
		requestConf['header'] = {
			'Authorization':userInfo.token,
		}
	}
	


	if (!options.closeLoading) {
		loadding.show();
	}
	uni.request(requestConf);

}


export default _request
